<template>
  <div class="tagsCointainer">
    <el-scrollbar w-full>
      <div class="flex">
        <el-tag
          class="tag"
          v-for="tag in visitedViews"
          :key="tag.path"
          :closable="!isAffixTag(tag)"
          @close="removeTag(tag)"
        >
          <RouterLink
            :class="{ tagLink: true, isActive: tag.path === route.path }"
            :to="tag.path"
          >
            <el-dropdown
              placement="bottom"
              trigger="contextmenu"
              @command="($event) => handleCommand($event, tag)"
            >
              <span> {{ (tag as any).title }} </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="all">关闭所有</el-dropdown-item>
                  <el-dropdown-item command="other">关闭其他</el-dropdown-item>
                  <el-dropdown-item command="current" v-if="!isAffixTag(tag)">
                    关闭当前
                  </el-dropdown-item>
                  <el-dropdown-item command="refresh">刷新</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </RouterLink>
        </el-tag>
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup lang="ts" name="TagsView">
import { useTagsViewStore } from "@/store/tagsView"
import path from "path-browserify"
import type { RouteLocationNormalizedGeneric, RouteRecordRaw } from "vue-router"
import { routes } from "@/router"
import { useSettingStore } from "@/store/setting"
const store = useTagsViewStore()
const settingStore = useSettingStore()
const {
  addView,
  delView,
  delAllViews,
  delOtherViews,
  delCurrentView,
  delCacheView
} = store
// visitedViews原来是ref数组,解构之后会变成reactive数组,然后重新赋值就会丢失响应式
const { visitedViews } = storeToRefs(store)
const route = useRoute()
const router = useRouter()

const isAffixTag = (tag: RouteLocationNormalizedGeneric) => {
  return tag.meta?.affix
}

const filterAffixRoutes = (routes: RouteRecordRaw[], basePath = "/") => {
  const affixRoutes: RouteLocationNormalizedGeneric[] = []
  for (const route of routes) {
    if (route.meta?.affix) {
      affixRoutes.push({
        name: route.name,
        path: path.join(basePath, route.path),
        meta: route.meta
      } as RouteLocationNormalizedGeneric)
    }
    if (route.children) {
      const tempRoutes = filterAffixRoutes(route.children, route.path)
      if (tempRoutes.length >= 1) {
        affixRoutes.push(...tempRoutes)
      }
    }
  }
  return affixRoutes
}

const initTags = () => {
  const affixRoutes = filterAffixRoutes(routes)
  console.log("affixRoutes", affixRoutes)

  affixRoutes.forEach((route) => {
    if (route.name) {
      addView(route)
    }
  })

  addTags()
}

onMounted(() => {
  initTags()
})

const addTags = () => {
  if (route.name) {
    addView(route)
  }
}

watch(() => route.path, addTags, {
  immediate: true
})

const removeTag = (tag: RouteLocationNormalizedGeneric) => {
  if (tag.meta.affix) return
  if (tag.path === route.path) {
    const index = visitedViews.value.findIndex((item) => item.path === tag.path)
    const next = visitedViews.value[index + 1] || visitedViews.value[index - 1]

    if (next) {
      router.push(next.path)
      delView(tag)
    } else {
      if (tag.path !== "/dashboard") {
        router.push("/")
        delView(tag)
      }
    }
  } else {
    delView(tag)
  }
}

const delAllTags = (tag: RouteLocationNormalizedGeneric) => {
  delAllViews()
  if (tag.path !== "/dashboard") {
    router.push("/")
  }
}

const delOtherTags = (tag: RouteLocationNormalizedGeneric) => {
  delOtherViews(tag)
  if (tag.path !== route.path) {
    // 跳当前点击的或者dashboard都可以
    router.push(tag.path)
  }
}

const delCurrentTag = (tag: RouteLocationNormalizedGeneric) => {
  const index = visitedViews.value.findIndex((item) => item.path === tag.path)
  delCurrentView(tag)
  // 如果删的是自己, 需要往前后跳(也可以跳dashboard)
  if (tag.path === route.path) {
    const next = visitedViews.value[index + 1] || visitedViews.value[index - 1]
    if (next) {
      router.push(next.path)
    }
  }
}

const enum commandEnum {
  ALL = "all",
  OTHER = "other",
  CURRENT = "current",
  REFRESH = "refresh"
}

const handleCommand = (
  command: commandEnum,
  route: RouteLocationNormalizedGeneric
) => {
  switch (command) {
    case commandEnum.ALL:
      delAllTags(route)
      break
    case commandEnum.OTHER:
      delOtherTags(route)
      break
    case commandEnum.CURRENT:
      delCurrentTag(route)
      break
    case commandEnum.REFRESH:
      delCacheView(route)
      router.push("/redirect" + route.path)
      break
  }
}
</script>

<style scoped lang="scss">
:deep(.el-tag .el-tag__close) {
  color: #606266;
  &:hover {
    // @apply bg-#ffbd7a text-#ffffff;
    background-color: v-bind("settingStore.theme");
    color: #ffffff;
  }
}

.tagsCointainer {
  @apply h-[34px] flex items-center pl-[10px] pr-[10px] overflow-x-auto;
  border-bottom: 1px solid #ccc;

  :deep(.el-scrollbar__wrap) {
    @apply flex items-center;
  }
  .tag {
    @apply h-[24px] decoration-none mr-[10px] cursor-pointer bg-#ffffff border-#ccc;

    .tagLink {
      @apply decoration-none text-black;
      &:hover {
        color: v-bind("settingStore.theme");
      }
    }

    .isActive {
      :deep(.el-dropdown) {
        // @apply text-#ffbd7a;
        color: v-bind("settingStore.theme");
      }
      &::before {
        content: "";
        @apply inline-block w-[8px] h-[8px] rounded-full mr-[5px];
        background-color: v-bind("settingStore.theme");
      }
    }
  }
}
// 修改滚动条样式
// ::-webkit-scrollbar {
//   width: 6px;
//   height: 6px;
// }
// ::-webkit-scrollbar-thumb {
//   border-radius: 6px;
//   background-color: #ccc;
// }
</style>
